import pygame
import random

from pygame.sprite import Sprite


class Alien(Sprite):
    """外星人"""
    def __init__(self, ai_settings, screen):
        """初始化外星人,并设置外星人的初始位置，"""
        self.screen = screen
        super(Alien, self).__init__()

        # 随机偏移量
        self.offset = random.randint(5, 333)

        #加载外星人的图片以及获取外星人矩形区域
        self.image = pygame.image.load(r'image\alien.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #使外星人初始位置为顶部,横向位置随机
        self.rect.top = self.screen_rect.top
        self.rect.centerx = random.uniform(0, self.screen_rect.width)

        #使外星人竖直方向坐标为浮点型
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

        #获取外形人的垂直速度和水平速度
        self.vertical_speed_factor = ai_settings.alien_vertical_speed_factor
        self.horizontal_speed_factor = ai_settings.alien_horizontal_speed_factor

    #对外形人的位置进行更新
    def update(self):

        #外星人向下移动以及横向移动坐标的更新
        self.y += self.vertical_speed_factor
        self.x += self.horizontal_speed_factor
        self.rect.x = self.x
        self.rect.y = self.y

        # 不断改变速度
        self.horizontal_speed_factor = random.uniform(1.1, 1.8) * (
            self.horizontal_speed_factor // abs(self.horizontal_speed_factor))

    #检测外形人是否超出屏幕
    def check(self):
        if self.rect.left < self.offset:
            self.horizontal_speed_factor = abs(self.horizontal_speed_factor)
        if self.rect.right + self.offset > self.screen_rect.width:
            self.horizontal_speed_factor = abs(
                self.horizontal_speed_factor) * -1

    #在指定位置绘制外星人
    def blitme(self):
        self.screen.blit(self.image, self.rect)

    def random_offset(self):
        self.offset = random.randint(5, 444)
